package com.gitlab.lucky.weixin.web.pay;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.gitlab.lucky.common.dao.model.WeixinGzhIntegrationRecord;
import com.gitlab.lucky.common.dao.model.WeixinGzhRecharge;
import com.gitlab.lucky.common.dao.model.WeixinGzhUser;
import com.gitlab.lucky.common.enums.CodeEnum;
import com.gitlab.lucky.common.enums.Constant;
import com.gitlab.lucky.common.utils.CookieUtil;
import com.gitlab.lucky.common.utils.IPUtils;
import com.gitlab.lucky.weixin.service.WeixinGzhMsgService;
import com.gitlab.lucky.weixin.service.WeixinGzhIntegrationRecordService;
import com.gitlab.lucky.weixin.service.WeixinGzhRechargeService;
import com.gitlab.lucky.weixin.service.WeixinGzhUserService;
import com.gitlab.lucky.weixin.web.pay.wxpay.WXPayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @program: lucky
 * @author: Mr.Han
 * @create: 2018-12-18 15:25
 **/
@Controller
public class NBFLZXPAYController {
    public static final Logger LOGGER = LoggerFactory.getLogger(NBFLZXPAYController.class);
    @Autowired
    private WeixinGzhUserService weixinGzhUserService;
    @Autowired
    private WeixinGzhMsgService weixinGzhMsgService;
    @Autowired
    private WeixinGzhIntegrationRecordService weixinGzhIntegrationRecordService;
    @Autowired
    private WeixinGzhRechargeService weixinGzhRechargeService;
    private final static String NBFLZX_APP_ID = "wxbe42bedf2693c0c5";
    private final static String NBFLZX_MCH_ID = "1531990581";
    private final static String NBFLZX_MCH_SECRET = "i0ayx33jvka2cp3gl23ap1a41jmhafei";
    private final static String WX_CREATE_ORDER = "https://api.mch.weixin.qq.com/pay/unifiedorder";

    //得到openId跳转到支付页面
    @GetMapping("nbflzx")
    public ModelAndView nbflzxpay(HttpServletRequest request, HttpServletResponse response,String platform) throws IOException {
        String openid_2 = CookieUtil.getCookie(request, Constant.OPENID + platform);
        if (openid_2 == null) {
            response.sendRedirect("/code?platform="+ platform + "&redirectUrl=/nbflzx?platform="+platform);
            return null;
        }
        ModelAndView m = new ModelAndView();
        m.setViewName("wxpay");
        m.addObject("openId", openid_2);
        return m;
    }

    @PostMapping("nbflzx_create_pay")
    @ResponseBody
    public String nbflzx_create_pay(String openId, Integer priceId, HttpServletRequest request) throws Exception {
        String ipAddr = IPUtils.getIpAddr(request);
        HashMap<String, String> map = new HashMap<>();
        map.put("appid", NBFLZX_APP_ID);
        map.put("mch_id", NBFLZX_MCH_ID);
        map.put("nonce_str", WXPayUtil.generateNonceStr());
        map.put("body", "内部福利中心");
        map.put("out_trade_no", UUID.randomUUID().toString().substring(0, 8));
        map.put("attach", NBFLZX_MCH_ID + "---" + openId);
        map.put("spbill_create_ip", ipAddr);
        map.put("trade_type", "JSAPI");
        map.put("notify_url", "http://wm.cgygeo.com/nbflzx_notifyUrl");
        if (priceId == 0) {
            map.put("total_fee", "100");
        }
        if (priceId == 1) {
            map.put("total_fee", "500");
        }
        if (priceId == 2) {
            map.put("total_fee", "1000");
        }
        if (priceId == 3) {
            map.put("total_fee", "2000");
        }
        map.put("openid", openId);
        try {
            String s = WXPayUtil.generateSignature(map, NBFLZX_MCH_SECRET);
            map.put("sign", s);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //转xml
        String s = WXPayUtil.mapToXml(map);
        String post = HttpUtil.post(WX_CREATE_ORDER, s);
        Map<String, String> stringStringMap = WXPayUtil.xmlToMap(post);
        String b = "prepay_id=" + stringStringMap.get("prepay_id");
        Map<String, String> objectObjectMap = new HashMap<>();
        objectObjectMap.put("appId", NBFLZX_APP_ID);
        objectObjectMap.put("timeStamp", new Date().getTime() + "");
        objectObjectMap.put("nonceStr", WXPayUtil.generateNonceStr());
        objectObjectMap.put("package", b);
        objectObjectMap.put("signType", "MD5");
        objectObjectMap.put("paySign", WXPayUtil.generateSignature(objectObjectMap, NBFLZX_MCH_SECRET));
        String s1 = JSONObject.toJSONString(objectObjectMap);
        return s1;
    }

    @PostMapping("nbflzx_notifyUrl")
    @ResponseBody
    public void nbflzx_notifyUrl(HttpServletRequest request, HttpServletResponse response) {
        //System.out.println("微信支付成功,微信发送的callback信息,请注意修改订单信息");
        InputStream is = null;
        try {
            is = request.getInputStream();//获取请求的流信息(这里是微信发的xml格式所有只能使用流来读)
            String xml = WXPayUtil.inputStream2String(is, "UTF-8");
            Map<String, String> notifyMap = WXPayUtil.xmlToMap(xml);//将微信发的xml转map

            if (notifyMap.get("return_code").equals("SUCCESS")) {
                if (notifyMap.get("result_code").equals("SUCCESS")) {
                    String ordersSn = notifyMap.get("out_trade_no");//商户订单号
                    Integer amountpaid = Integer.parseInt(notifyMap.get("total_fee"));//实际支付的订单金额:单位 分
                    String openid = notifyMap.get("openid");  //如果有需要可以获取
                    //String trade_type = notifyMap.get("trade_type");
                    WeixinGzhIntegrationRecord weixinGzhIntegrationRecord = new WeixinGzhIntegrationRecord();
                    WeixinGzhUser weixinGzhUser = weixinGzhUserService.getWxUserInfoByOpenId(openid, 2);
                    if (amountpaid == 100) {
                        weixinGzhIntegrationRecord.setIntegration("+"+10);
                        weixinGzhUser.setIntegration(weixinGzhUser.getIntegration() + 10);
                    }
                    if (amountpaid == 500) {
                        weixinGzhIntegrationRecord.setIntegration("+"+80);
                        weixinGzhUser.setIntegration(weixinGzhUser.getIntegration() + 80);
                    }
                    if (amountpaid == 1000) {
                        weixinGzhIntegrationRecord.setIntegration("+"+160);
                        weixinGzhUser.setIntegration(weixinGzhUser.getIntegration() + 160);
                    }
                    if (amountpaid == 2000) {
                        weixinGzhIntegrationRecord.setIntegration("+"+360);
                        weixinGzhUser.setIntegration(weixinGzhUser.getIntegration() + 360);
                    }
                    weixinGzhUserService.updateByPrimaryKeySelective(weixinGzhUser);
                    //积分流水记录
                    weixinGzhIntegrationRecord.setIntegrationBalance(weixinGzhUser.getIntegration());
                    weixinGzhIntegrationRecord.setOpenId(weixinGzhUser.getOpenid());
                    weixinGzhIntegrationRecord.setPlatform(2);
                    weixinGzhIntegrationRecord.setCreateTime(new Date());
                    weixinGzhIntegrationRecord.setType(CodeEnum.RECHARGE.getCode());
                    weixinGzhIntegrationRecordService.insert(weixinGzhIntegrationRecord);
                    //充值记录
                    WeixinGzhRecharge weixinGzhRecharge = new WeixinGzhRecharge();
                    weixinGzhRecharge.setCreateTime(new Date());
                    weixinGzhRecharge.setMoney(amountpaid/100.00);
                    weixinGzhRecharge.setOpenId(openid);
                    weixinGzhRecharge.setParentOpenId(weixinGzhUser.getQrSceneStr());
                    weixinGzhRecharge.setPlatform(2);
                    weixinGzhRecharge.setState(Constant.NO_WITHDRAWAL);
                    weixinGzhRechargeService.insertSelective(weixinGzhRecharge);weixinGzhMsgService.resultServerText(weixinGzhUser.getOpenid(), String.format(Constant.PAY_MSG, weixinGzhUser.getIntegration()), 2);
                }
            }
            //告诉微信服务器收到信息了，不要在调用回调action了========这里很重要回复微信服务器信息用流发送一个xml即可
            response.getWriter().write("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>");
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
